package com.globallogic.dailyplanner.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.globallogic.dailyplanner.dto.RoleEnum;
import com.globallogic.dailyplanner.dto.User;
import com.globallogic.dailyplanner.repository.UserRepository;
import com.globallogic.dailyplanner.service.UserService;

@Service
public class UserServiceImpl implements UserService{
	
	@Autowired
	private UserRepository userRepository;

	@Override
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<User> getAll() {
		return userRepository.findAll(new Sort(Sort.Direction.ASC,"active"));
	}

	@Override
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public User getById(int id) {
		return userRepository.findOne(id);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRES_NEW, timeout=30)
	public User save(User user) {
		return userRepository.saveAndFlush(user);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRES_NEW, timeout=30)
	public void kill(int userId) {
		userRepository.delete(userId);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRES_NEW, timeout=30)
	public void activate(int userId) {
		User user = userRepository.findOne(userId);
		user.setActive(true);
		userRepository.saveAndFlush(user);
	}

	@Override
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public User findOneByName(String username) {
		return userRepository.findOneByUsername(username);
	}

	@Override
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public User getByEmail(String email) {
		return userRepository.findOneByEmail(email);
	}

	@Override
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public long getUsersByStatusAndRole(boolean status, RoleEnum role) {
		return userRepository.getUserCountByStatus(status, role);
	}	
}
